﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fly.Common.Linq;
using Newtonsoft.Json;
using Telerik.Web.UI;
using System.Configuration;

namespace RN.ERP.Web.Person
{
    public partial class PersonEmpListShow : BasePage
    {
        #region  公共属性
        /// <summary>
        /// 登陆用户guid
        /// </summary>
        protected string CorpUserGuid
        {
            get
            {
                return UserInfo.CorpUserGuid;
            }
        }
        /// <summary>
        /// 当前市场
        /// </summary>
        protected string AreaCode
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }
        /// <summary>
        /// 登陆用户类型
        /// </summary>
        protected string RoleType
        {
            get
            {
                return UserInfo.RoleType;
            }
        }
        /// <summary>
        /// 登录用户roleid
        /// </summary>
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }
        /// <summary>
        /// 作为查询地区限定条件
        /// </summary>
        protected string AreaCodeWhere
        {
            get
            {
                return UserInfo.AreaCode;
            }
        }
        /// <summary>
        /// 标识在管理端通过企业guid查询列表
        /// </summary>
        protected string tag
        {
            get
            {
                return ViewState["tag"].ToString();
            }
        }
        /// <summary>
        /// 人员类型
        /// </summary>
        private int classId;

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initial();
            }
        }
        #region 页面设置
        /// <summary>
        /// 参数及设置按钮显示
        /// </summary>
        private void Initial()
        {
            int opt = 0;//默认是一级页面
            string areaCode = string.Empty;
            string flowCode = string.Empty;
            ////人员类型
            if (Request.QueryString["classId"] != null)
            {
                int.TryParse(Request.QueryString["classId"].Trim(), out classId);
            }
            hdClassId.Value = classId.ToString();

            //表示是否从统计页面来
            if (Request.QueryString["opt"] != null)
            {
                int.TryParse(Request.QueryString["opt"].Trim(), out opt);
            }
            //统计页面参数-地区号
            if (Request.QueryString["areacode"] != null)
            {
                areaCode = Request.QueryString["areacode"].Trim();
            }
            //统计页面参数-审核状态
            if (Request.QueryString["flowcode"] != null)
            {
                flowCode = Server.UrlDecode(Request.QueryString["flowcode"].Trim());
            }
            ////证书类型
            if (Request.QueryString["itemType"] != null)
            {
                FormatQueryParam(Request.QueryString["itemType"].Trim());
            }
            ViewState["opt"] = opt;
            ViewState["areaCode"] = areaCode;
            ViewState["flowCode"] = flowCode;
            ViewState["tag"] = 0;
            ///用户端登陆
            SetUsersShow();
            //企业Guid
            if (!string.IsNullOrEmpty(Request.QueryString["corpUserGuid"]))
            {
                ViewState["tag"] = 1;//标识在通过企业guid查询列表
                hdCorpUserGuid.Value = Request.QueryString["corpUserGuid"].Trim();
            }
            else
            {
                hdCorpUserGuid.Value = CorpUserGuid;
            }
            string appid = ConfigurationManager.AppSettings["AppId"];

        }
        /// <summary>
        /// 根据用户页配置面内容
        /// </summary>
        private void SetUsersShow()
        {
            if (RoleType == "User")
            {
                UserDiv.Visible = true;//企业端操作按钮div
                ///用户端登陆
                hdCorpUserGuid.Value = CorpUserGuid;
                return;
            }
     
        }
        /// <summary>
        /// 取得证书类型参数--参数格式：x,x或1;x,x
        /// </summary>
        /// <param name="itemType"></param>
        private void FormatQueryParam(string itemType)
        {
            if (itemType.Contains(";"))
            {
                hdEmpItemFlag.Value = itemType.Split(';')[0];
                hdEmpItemType.Value = itemType.Split(';')[1];
            }
            else
            {
                hdEmpItemType.Value = itemType;
            }

        }

        #endregion

        #region 取得数据源
        /// <summary>
        /// 取得人员信息参数列表
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions()
        {
            List<ModelService.QueryPersonInfoCondition> query = new List<ModelService.QueryPersonInfoCondition>();
            
            ModelService.QueryPersonInfoCondition queryCondition = GetQueryCondition(string.Empty);
            query.Add(queryCondition);
          
            return JsonConvert.SerializeObject(query);
        }
        /// <summary>
        /// 取得人员参数项
        /// </summary>
        /// <param name="flowCode"></param>
        /// <returns></returns>
        private ModelService.QueryPersonInfoCondition GetQueryCondition(string flowCode)
        {
            ///设置查询参数
            ModelService.QueryPersonInfoCondition queryCondition = new ModelService.QueryPersonInfoCondition();
            //queryCondition.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
            int.TryParse(hdClassId.Value, out classId);
            //人员类型
            if (classId > 0)
            {
                queryCondition.ClassId = new ParameterValue<int?> { V = classId, O = OptEnum.Equal };
            }
            
            //人员名称
            if (!string.IsNullOrEmpty(txtEmpName.Text.Trim()))
            {
                queryCondition.Name = new ParameterValue<string> { V = txtEmpName.Text.Trim(), O = OptEnum.Like };
            }
            ///身份证
            if (!string.IsNullOrEmpty(txtEmpIdCard.Text.Trim()))
            {
                queryCondition.IDCard = new ParameterValue<string> { V = txtEmpIdCard.Text.Trim(), O = OptEnum.Equal };
            }            
            
            return queryCondition;
        }
        /// <summary>
        /// 绑定人员数据列表
        /// </summary>
        private void rgPersonDataBind()
        {
            int currentPageIndex = rgPersonList.CurrentPageIndex;
            int pageSize = rgPersonList.MasterTableView.PageSize;
            int count = 0;
            string result = string.Empty;
            try
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string conditions = GetQueryConditions();

                    result = client.GetAllEmpManagerList(conditions, currentPageIndex + 1, pageSize, hdCorpUserGuid.Value, AreaCode, out count);
                    rgPersonList.VirtualItemCount = count;
                    rgPersonList.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                }
            }
            catch
            { }
        }

        /// <summary>
        /// 绑定查询列表
        /// </summary>
        private void PersonDataBind()
        {
            //将高级查询和统计查询条件置空
            hdSearchEndStr.Value = "";
            ViewState["opt"] = 0;
            ViewState["areaCode"] = "";
            ViewState["flowCode"] = "";
            rgPersonList.CurrentPageIndex = 0;
            rgPersonDataBind();
            rgPersonList.DataBind();
        }
        #endregion

        #region 事件处理
        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnEmpSreach_Click(object sender, EventArgs e)
        {
            PersonDataBind();
        }

        /// <summary>
        /// 绑定人员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void rgPersonList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            rgPersonDataBind();
        }
        
        /// <summary>
        /// 修改人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdatePerson_Click(object sender, EventArgs e)
        {
            string empGuid = GetSelCheck();
            if (string.IsNullOrEmpty(empGuid))
            {
                RadWindowManager1.RadAlert("请选择要操作的项！", 300, 150, "提示", "");
            }
            if (empGuid.IndexOf(",") > 0)
            {
                RadWindowManager1.RadAlert("只能选择一个修改项！", 300, 150, "提示", "");
            }
            string url = string.Format("PersonEmpInfo.aspx?empGuid={0}&typeFlag={1}", empGuid, "-1");

            Response.Redirect(url, true);
        }
        
        /// <summary>
        /// 取得客户端选择的项
        /// </summary>
        /// <returns></returns>
        private string GetSelCheck()
        {
            string empGuid = string.Empty;
            foreach (GridDataItem item in rgPersonList.Items)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox box = (System.Web.UI.HtmlControls.HtmlInputCheckBox)item.FindControl("ckb");
                if (box.Checked)
                {
                    empGuid = box.Value.Trim() + ",";
                }
            }
            if (empGuid.Length > 1)
            {
                empGuid = empGuid.TrimEnd(',');
            }
            return empGuid;
        }

        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Rebind")
            {
                rgPersonList.MasterTableView.SortExpressions.Clear();
                rgPersonList.MasterTableView.GroupByExpressions.Clear();
                rgPersonList.Rebind();
            }

        }

        #endregion

        protected void rgPersonList_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                var currentItem = e.Item as GridDataItem;
                var value = currentItem["EmployeeType"].Text;
                if (value == "100")
                {
                    e.Item.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected string GetRepeateButton(int type, string IDCard)
        {
            string result = type == 100 ? "<input id=\"btnViewRepeat\" type=\"button\" value=\"查看重复\" style=\"border: 2\"  onclick=\"ViewRepeatList('" + IDCard + "')\" />" : "";
            return result;
        }
    }
}